<template>
  <div class="media">
    <div class="eye-area">
      <!-- 左眼部分 -->
      <div class="left">
        <h1 class="eye-title">左眼</h1>
        <video class="video" width="50%" height="auto" ref="left_video" autoplay :srcObject="left_videoSource">
          Video stream not available.
        </video>
        <canvas width="500" height="375" ref="left_canvas" id="left_canvas" style="display: none;" />
        <div class="button-container">
          <button class="capture-button" @click="takePhoto('left')">确认拍照</button>
          <button class="capture-button" @click="retakePhoto('left')">重拍</button>
        </div>
      </div>

      <!-- 右眼部分 -->
      <div class="right">
        <h1 class="eye-title">右眼</h1>
        <video class="video" width="50%" height="auto" ref="right_video" autoplay :srcObject="right_videoSource">
          Video stream not available.
        </video>
        <canvas width="500" height="375" ref="right_canvas" id="right_canvas" style="display: none;" />
        <div class="button-container">
          <button class="capture-button" @click="takePhoto('right')">确认拍照</button>
          <button class="capture-button" @click="retakePhoto('right')">重拍</button>
        </div>
      </div>
    </div>

    <!-- 图片预览区域 -->
    <div class="photo-preview">
      <div class="photo-grid left-photos">
        <img v-for="(photo, index) in leftPhotos" :key="index" :src="photo" class="preview-photo"
          @dblclick="removePhoto(index, 'left')" />
      </div>
      <div class="photo-grid right-photos">
        <img v-for="(photo, index) in rightPhotos" :key="index" :src="photo" class="preview-photo"
          @dblclick="removePhoto(index, 'right')" />
      </div>
    </div>

    <div class="button-container">
      <button class="capture-button">灯光自动控制</button>
      <input type="range" class="light-control" min="0" max="100" value="50" style="margin: 0 10px;">
      <button class="capture-button" @click="startDiagnosis" style="margin:0 12%;">开始诊断</button>
      <button class="capture-button">自动对焦</button>
    </div>


    <!-- 加载提示模态框 -->
    <div class="modal" @click="handleOutsideClick" v-if="isProcessing">
      <div class="modal-dialog" @click.stop>
        <div class="modal-content">
          <div class="modal-body">
            <p style="font-weight: bold; font-size:x-large;">上传成功</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { MessageBox } from 'element-ui';
// import * as qiniu from 'qiniu-js';


export default {
  data() {
    return {
      left_videoSource: null,
      right_videoSource: null,
      caseNo: localStorage.getItem("caseNo"),
      backendUrl: process.env.VUE_APP_BACKEND_URL || 'https://yzulcy.top/eye/collect',
      isProcessing: false,
      cameraName: 'USB2.0 Camera RGB', // 摄像头名称
      cameraDeviceId: null, // 摄像头 deviceId
      leftPhotos: [], // 存储左眼拍摄的照片
      rightPhotos: [] // 存储右眼拍摄的照片
    };
  },

  mounted() {
    // console.log('===============================');
    // this.getPhotoURL();
    this.$nextTick(() => {
      this.enumerateDevices().then(cameraId => {
        if (cameraId) {
          this.cameraDeviceId = cameraId;
          this.getCameraStream();
        } else {
          console.error(`没有找到名为 "${this.cameraName}" 的摄像头`);
        }
      });
    });
  },

  methods: {
    async enumerateDevices() {
      const devices = await navigator.mediaDevices.enumerateDevices();
      const camera = devices.find(device => device.kind === 'videoinput' && device.label.includes(this.cameraName));
      console.log('Available devices:', devices);
      console.log('Available camera:', camera);
      this.cameraName = camera ? camera.label : ''; // 存储摄像头名称
      return camera ? camera.deviceId : null;
    },

    getCameraStream() {
      const constraints = this.cameraDeviceId
        ? { video: { deviceId: { exact: this.cameraDeviceId } } }
        : { video: true };

      navigator.mediaDevices.getUserMedia(constraints)
        .then(stream => {
          const left_video = this.$refs.left_video;
          const right_video = this.$refs.right_video;

          if (left_video && right_video) {
            this.left_videoSource = stream;
            left_video.srcObject = stream;
            left_video.play();

            this.right_videoSource = stream;
            right_video.srcObject = stream;
            right_video.play();
          } else {
            console.error('Video elements not found.');
          }
        })
        .catch(error => console.error('Error accessing the camera:', error));
    },

    takePhoto(side) {
      if (!this.$refs[`${side}_canvas`] || !this.$refs[`${side}_video`]) {
        return;
      }

      const video = this.$refs[`${side}_video`];
      const canvas = this.$refs[`${side}_canvas`];

      const ctx = canvas.getContext('2d');
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

      const photoSrc = canvas.toDataURL('image/png');

      // 根据侧别将新拍摄的照片添加到对应的照片数组中
      if (side === 'left') {
        this.leftPhotos.push(photoSrc);
        // 如果照片超过4张，则移除最早的一张
        if (this.leftPhotos.length > 4) {
          this.leftPhotos.shift();
        }
      } else if (side === 'right') {
        this.rightPhotos.push(photoSrc);
        // 如果照片超过4张，则移除最早的一张
        if (this.rightPhotos.length > 4) {
          this.rightPhotos.shift();
        }
      }
    },

    retakePhoto(side) {
      // 清空对应侧的照片
      if (side === 'left') {
        this.leftPhotos = [];
      } else if (side === 'right') {
        this.rightPhotos = [];
      }
    },

    async startDiagnosis() {
      try {
        if (this.leftPhotos.length + this.rightPhotos.length < 1) {
          alert('至少需要一张照片才能开始诊断！');
          return;
        }

        if (this.leftPhotos.length + this.rightPhotos.length > 8) {
          alert('最多只能选择八张照片进行诊断！');
          return;
        }

        this.isProcessing = true;
        if (!this.caseNo || this.caseNo.trim() === '') {
          throw new Error('病历号(caseNo)不能为空！');
        }

        // 准备FormData对象
        const formData = new FormData();
        formData.append('caseNo', this.caseNo);

        // 添加左眼照片
        for (let i = 0; i < this.leftPhotos.length; i++) {
          const imageBlob = await this.dataUrlToBlob(this.leftPhotos[i]);
          formData.append(`left`, imageBlob, `${this.caseNo}_left_${i + 1}.png`);
        }

        // 添加右眼照片
        for (let i = 0; i < this.rightPhotos.length; i++) {
          const imageBlob = await this.dataUrlToBlob(this.rightPhotos[i]);
          formData.append(`right`, imageBlob, `${this.caseNo}_right_${i + 1}.png`);
        }

        // 发送诊断请求
        const response = await axios.post(`${this.backendUrl}`, formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        });


        const result = response.data.data.data;
        localStorage.setItem('眼诊', result);
        // alert('诊断成功，请查看结果！');
      } catch (error) {
        // console.error('Error during diagnosis:', error);
        // alert('上传失败，请重试。');
      } finally {
        // this.isProcessing = false;
      }
    },


    dataUrlToBlob(dataUrl) {
      return new Promise((resolve) => {
        const byteString = atob(dataUrl.split(',')[1]);
        const arrayBuffer = new ArrayBuffer(byteString.length);
        const uint8Array = new Uint8Array(arrayBuffer);

        for (let i = 0; i < byteString.length; i++) {
          uint8Array[i] = byteString.charCodeAt(i);
        }

        resolve(new Blob([arrayBuffer], { type: 'image/png' }));
      });
    },

    handleOutsideClick(event) {
      if (event.target === event.currentTarget) {
        this.isProcessing = false;
      }
      window.localStorage.clear();
      this.$router.push({
        name: "Login"
      });
    },

    //双击删除图片
    removePhoto(index, side) {
      MessageBox.confirm('您确定要删除这张照片吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (side === 'left') {
          this.leftPhotos.splice(index, 1);
        } else if (side === 'right') {
          this.rightPhotos.splice(index, 1);
        }
      }).catch(() => {
        // 用户取消了删除操作
      });
    },
  },

};
</script>



<style scoped>
#app {
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}
.light-control {
  /* 根据需要调整滑动条样式 */
  -webkit-appearance: none; /* 移除默认样式 */
  width: 200px; /* 设置滑动条宽度 */
  height: 4px; /* 设置滑动条高度 */
  background: #ddd; /* 设置滑动条背景颜色 */
  outline: none; /* 移除聚焦时的轮廓线 */
  opacity: 0.7; /* 设置透明度 */
  -webkit-transition: .2s; /* 过渡效果 */
  transition: opacity .2s;
}

.light-control::-webkit-slider-thumb {
  -webkit-appearance: none; /* 移除默认样式 */
  appearance: none;
  width: 16px; /* 设置滑块宽度 */
  height: 16px; /* 设置滑块高度 */
  background: #4CAF50; /* 设置滑块颜色 */
  cursor: pointer; /* 设置鼠标样式为指针 */
}

.light-control::-moz-range-thumb {
  width: 16px; /* 设置滑块宽度 */
  height: 16px; /* 设置滑块高度 */
  background: #4CAF50; /* 设置滑块颜色 */
  cursor: pointer; /* 设置鼠标样式为指针 */
}

.eye-title {
  text-align: center;
  font-family: '华文楷体', '楷体', 'Arial', sans-serif;
  /* 使用更优雅的中文字体 */
  font-size: 1.5em;
  /* 调整字体大小 */
  color: #444;
  /* 更深一些的文字颜色 */
  letter-spacing: 2px;
  /* 增加字母间距 */
  line-height: 1;
  /* 行高 */
  margin-bottom: 5px;
  /* 底部边距 */
}

/* 定义媒体容器样式 */
.media {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.eye-area {
  display: flex;
  flex-direction: row;
}

.left,
.right {
  flex: 1;
  position: relative;
}

.video {
  width: 97%;
  height: auto;
  border-radius: 8px;
  overflow: hidden;
  background-image: url('@/assets/image/图片预览.png');
  background-size: cover;
  background-position: center;
  border: 2px solid #d3d2d2;
}

.image {
  position: absolute;
  top: 0;
  left: 0;
  width: 98%;
  height: 88%;
  object-fit: cover;
  border-radius: 8px;
}

.button-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.photo-preview {
  display: flex;
  justify-content: space-between;
}

.photo-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 1rem;
  width: 48%;
  /* 确保两个grid容器并排时不超过总宽度 */
}

.preview-photo {
  width: 100%;
  height: auto;
}

.capture-button {
  padding: 10px 20px;
  background-color: #007BFF;
  color: white;
  font-size: larger;
  font-weight: bold;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.1s ease;
  margin: 2%;
}

.capture-button:hover {
  background-color: #e1475e;
}

#left_canvas,
#right_canvas {
  display: none;
}

.modal {
  position: fixed;
  z-index: 1000;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-dialog {
  background-color: #fff;
  margin: 15% auto;
  padding: 20px;
  border-radius: 5px;
  width: 30%;
  text-align: center;
}

.modal-body p {
  font-size: 16px;
  color: #333;
}

.eye-area>div {
  flex: 1;
  display: inline-block;
  vertical-align: top;
  margin-right: 1rem;
}

@media (max-width: 600px) {
  .eye-area>div {
    margin-bottom: 1rem;
    margin-right: 0;
  }
}
</style>